# -*- coding: utf-8 -*-
from playwright.sync_api import sync_playwright, expect, Page
import os,time

URL_L = "https://192.168.4.195"


def page_login_save_cookies(page: Page, user_name: str, password: str):
    """
    通过页面登录
    :param page: page对象
    :param usernaem:
    :param password:
    :return:
    """

    # os.path.getatime(f"{user_name}.txt" 文件的创建时间
    # page.pause() # 断言

    if os.path.exists(f"{user_name}.txt") and int(time.time() - os.path.getatime(f"{user_name}.txt")) < 86400:
        page.context.clear_cookies()  # 清楚cookie
        with open(f"{user_name}.txt") as f:
            cookies = f.read()
        cookies = eval(cookies)  # 转换文档原格式
        page.context.add_cookies(cookies)
        page.goto("https://pingcode.com/signin")

    page.context.clear_cookies() # 清楚cookie
    page.goto("https://pingcode.com/signin")
    page.get_by_role("textbox", name="请输入手机号/邮箱").type(user_name, delay=100)
    page.get_by_role("textbox", name="请输入登录密码").fill(password)
    page.get_by_role("button", name="登录").click()
    expect(page.locator('.avatar-default').first).to_be_visible()  # to_be_visible 判断是否存在
    cookies = page.context.cookies()
    with open(f"{user_name}.txt", "w") as f:
        f.write(str(cookies))
